package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import dao.Blog;
import dao.BlogDao;
import dao.User;
import dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/user")
public class UserServlet extends HttpServlet {
    ObjectMapper objectMapper=new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String bolgId=req.getParameter("blogId");
        if(bolgId==null)
        {
            HttpSession session=req.getSession(false);
            if(session==null) {
                User user = new User();
                String respJson = objectMapper.writeValueAsString(user);//构造一个json对象
                resp.setContentType("application/json; charset=utf8");
                resp.getWriter().write(respJson);//写回响应
                return;
            }
            User user=(User) session.getAttribute("user");
              if(user==null) {
                  user = new User();
                  String respJson = objectMapper.writeValueAsString(user);//构造一个json对象
                  resp.setContentType("application/json; charset=utf8");
                  resp.getWriter().write(respJson);
                  return;
              }
            String respJson = objectMapper.writeValueAsString(user);//构造一个json对象
            resp.setContentType("application/json; charset=utf8");
            resp.getWriter().write(respJson);
        }
        else
        {
            //拿到博客id，就需要查询
            BlogDao blogDao=new BlogDao();//连接数据库
            Blog blog=blogDao.getBlog(Integer.parseInt(bolgId));//通过id查询
            //如果查不到
            if(blog==null)
            {
                User user=new User();//返回一个空对象
                String respJson = objectMapper.writeValueAsString(user);//构造一个json对象
                resp.setContentType("application/json; charset=utf8");
                resp.getWriter().write(respJson);
                return;
            }
            UserDao userDao=new UserDao();
            User user=userDao.getUserById(blog.getUserId());
            if(user==null) {//当查找不到user的时候返回到一个空的对象
                user = new User();
                String respJson = objectMapper.writeValueAsString(user);//构造一个json对象
                resp.setContentType("application/json; charset=utf8");
                resp.getWriter().write(respJson);
                return;
            }//找到了用户会会构造出一个AJAX对象
            String respJson = objectMapper.writeValueAsString(user);//构造一个json对象
            resp.setContentType("application/json; charset=utf8");
            resp.getWriter().write(respJson);
        }

    }
}
